import { Typography, Tag, Divider, List, Button, Empty, Space, message, Tooltip } from 'antd';
import { Link, useParams } from 'react-router-dom';
import { CalendarOutlined, TagOutlined, UserOutlined, EditOutlined, EyeOutlined, CopyOutlined, CheckOutlined } from '@ant-design/icons';
import React, { useState, useEffect } from 'react';
import ReactMarkdown from 'react-markdown';
import rehypeRaw from 'rehype-raw';
import rehypeHighlight from 'rehype-highlight';
import remarkGfm from 'remark-gfm';
import 'highlight.js/styles/github.css';

import dataService from '../../services/dataService';
import type { BlogPost } from '../../services/dataService'
import './BlogPage.scss';

const { Title, Paragraph, Text } = Typography;

const BlogPage: React.FC = () => {
  const { id, category } = useParams();
  const [blogPost, setBlogPost] = useState<BlogPost | null>(null);
  const [blogPosts, setBlogPosts] = useState<BlogPost[]>([]);
  const [loading, setLoading] = useState(true);
  // 解析markdown标题，生成导航项
  const [headings, setHeadings] = useState<Array<{id: string, text: string, level: number}>>([]);
  const [activeHeading, setActiveHeading] = useState<string>('');
  // 编辑相关状态
  const [isEditing, setIsEditing] = useState(false);
  const [editContent, setEditContent] = useState('');
  const [preview, setPreview] = useState(false);
  // 代码复制状态
  const [copiedCode, setCopiedCode] = useState<string | null>(null);

  useEffect(() => {
    const fetchData = async () => {
      setLoading(true);
      try {
        if (id) {
          // 获取单篇博客文章
          const post = dataService.getBlogPostById(id);
          setBlogPost(post || null);
        } else if (category) {
          // 获取特定分类的博客文章
          let categoryName = '所有文章';
          if (category === 'tech') {
            categoryName = '技术文章';
          } else if (category === 'life') {
            categoryName = '生活随笔';
          }
          const posts = category === 'all' 
            ? dataService.getBlogPosts() 
            : dataService.getBlogPostsByCategory(categoryName);
          setBlogPosts(posts);
        } else {
          // 获取所有博客文章
          const posts = dataService.getBlogPosts();
          setBlogPosts(posts);
        }
      } catch (error) {
        console.error('获取博客数据失败:', error);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [id, category]);

  // 手动解析markdown内容提取标题
  useEffect(() => {
    if (blogPost && blogPost.content) {
      const newHeadings: Array<{id: string, text: string, level: number}> = [];
      const headingRegex = /^(#{2,6})\s+([^\n]+)/gm;
      let match;
      
      while ((match = headingRegex.exec(blogPost.content)) !== null) {
        const level = match[1].length;
        const text = match[2].trim();
        // 生成唯一ID
        const id = text.toLowerCase().replace(/\s+/g, '-').replace(/[^\w-]/g, '');
        newHeadings.push({
          id,
          text,
          level
        });
      }
      
      setHeadings(newHeadings);
    }
  }, [blogPost]);

  // 滚动监听函数
  useEffect(() => {
    const handleScroll = () => {
      const scrollPosition = window.scrollY + 100;
      
      // 从底部向上查找可见的标题
      for (let i = headings.length - 1; i >= 0; i--) {
        const heading = document.getElementById(headings[i].id);
        if (heading && heading.offsetTop <= scrollPosition) {
          setActiveHeading(headings[i].id);
          break;
        }
      }
      
      // 如果没有找到任何可见的标题，则设置为第一个
      if (!activeHeading && headings.length > 0) {
        setActiveHeading(headings[0].id);
      }
    };

    // 注册滚动监听
    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll);
  }, [headings, activeHeading]);

  // 自定义渲染器，为标题添加id，为代码块添加复制功能
  const components = {
    h2: ({ children }: any) => {
      const text = React.Children.map(children, child => typeof child === 'string' ? child : '').join('');
      const id = text.toLowerCase().replace(/\s+/g, '-').replace(/[^\w-]/g, '');
      return (
        <h2 id={id} className="markdown-heading">
          {children}
        </h2>
      );
    },
    h3: ({ children }: any) => {
      const text = React.Children.map(children, child => typeof child === 'string' ? child : '').join('');
      const id = text.toLowerCase().replace(/\s+/g, '-').replace(/[^\w-]/g, '');
      return (
        <h3 id={id} className="markdown-heading">
          {children}
        </h3>
      );
    },
    h4: ({ children }: any) => {
      const text = React.Children.map(children, child => typeof child === 'string' ? child : '').join('');
      const id = text.toLowerCase().replace(/\s+/g, '-').replace(/[^\w-]/g, '');
      return (
        <h4 id={id} className="markdown-heading">
          {children}
        </h4>
      );
    },
    h5: ({ children }: any) => {
      const text = React.Children.map(children, child => typeof child === 'string' ? child : '').join('');
      const id = text.toLowerCase().replace(/\s+/g, '-').replace(/[^\w-]/g, '');
      return (
        <h5 id={id} className="markdown-heading">
          {children}
        </h5>
      );
    },
    h6: ({ children }: any) => {
      const text = React.Children.map(children, child => typeof child === 'string' ? child : '').join('');
      const id = text.toLowerCase().replace(/\s+/g, '-').replace(/[^\w-]/g, '');
      return (
        <h6 id={id} className="markdown-heading">
          {children}
        </h6>
      );
    },
    code: ({ node, inline, className, children, ...props }: any) => {
      const match = /language-(\w+)/.exec(className || '');
      const language = match ? match[1] : '';
      const code = String(children).replace(/\n$/, '');
      
      if (!inline && language) {
        return (
          <div className="code-block-wrapper">
            <div className="code-block-header">
              <span className="code-language">{language}</span>
              <Tooltip title={copiedCode === code ? '已复制' : '复制代码'}>
                <Button
                  type="text"
                  size="small"
                  icon={copiedCode === code ? <CheckOutlined /> : <CopyOutlined />}
                  onClick={() => copyCodeToClipboard(code)}
                  className="copy-button"
                />
              </Tooltip>
            </div>
            <pre className={`hljs ${className}`} {...props}>
              <code className={className}>{children}</code>
            </pre>
          </div>
        );
      }
      
      return (
        <code className={className} {...props}>
          {children}
        </code>
      );
    },
    pre: ({ children }: any) => {
      return <pre className="markdown-pre">{children}</pre>;
    }
  };
  
  // 渲染导航项
  const renderNavItem = (heading: {id: string, text: string, level: number}, index: number) => {
    // 根据标题级别添加不同的缩进
    const indent = (heading.level - 2) * 16;
    
    return (
      <div 
        key={index} 
        className={`nav-item ${activeHeading === heading.id ? 'active' : ''}`}
        style={{ paddingLeft: `${indent}px` }}
        onClick={() => {
          const element = document.getElementById(heading.id);
          if (element) {
            window.scrollTo({
              top: element.offsetTop - 80,
              behavior: 'smooth'
            });
          }
        }}
      >
        {heading.text}
      </div>
    );
  };

  // 格式化日期显示
  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return new Intl.DateTimeFormat('zh-CN', {
      year: 'numeric',
      month: 'long',
      day: 'numeric'
    }).format(date);
  };

  // 复制代码功能
  const copyCodeToClipboard = async (code: string) => {
    try {
      await navigator.clipboard.writeText(code);
      setCopiedCode(code);
      message.success('代码已复制到剪贴板');
      setTimeout(() => setCopiedCode(null), 2000);
    } catch (err) {
      message.error('复制失败');
    }
  };

  // 渲染博客文章详情
  const renderBlogPostDetail = () => {
    if (loading) {
      return <div style={{ textAlign: 'center', padding: '40px' }}>加载中...</div>;
    }

    if (!blogPost) {
      return (
        <div style={{ textAlign: 'center', padding: '40px' }}>
          <Empty description="文章不存在" />
          <Button type="primary" style={{ marginTop: 16 }}>
            <Link to="/blog">返回博客列表</Link>
          </Button>
        </div>
      );
    }

    return (
      <div className="blog-detail">
        <div className="blog-header">
          <Title level={1}>{blogPost.title}</Title>
          <div className="blog-meta">
            <Text type="secondary" className="blog-meta-item">
              <UserOutlined /> {blogPost.author}
            </Text>
            <Text type="secondary" className="blog-meta-item">
              <CalendarOutlined /> {formatDate(blogPost.createdAt)}
            </Text>
            {blogPost.updatedAt !== blogPost.createdAt && (
              <Text type="secondary" className="blog-meta-item">
                更新于 {formatDate(blogPost.updatedAt)}
              </Text>
            )}
            <Text type="secondary" className="blog-meta-item">
              <Tag color="blue">{blogPost.category}</Tag>
            </Text>
          </div>
        </div>
        
        <div style={{ marginBottom: '16px' }}>
          <Button 
            type="primary" 
            icon={<EditOutlined />} 
            onClick={() => {
              if (blogPost) {
                setEditContent(blogPost.content);
                setIsEditing(true);
                setPreview(false);
              }
            }}
          >
            编辑文章
          </Button>
        </div>
        
        <Divider />
        
        {isEditing ? (
          <div>
            <div className="blog-content-with-nav">
              <div className="markdown-editor-wrapper">
                <div style={{ marginBottom: '12px', textAlign: 'right' }}>
                  <Space>
                    <Button 
                      icon={preview ? <EditOutlined /> : <EyeOutlined />}
                      onClick={() => setPreview(!preview)}
                    >
                      {preview ? '编辑' : '预览'}
                    </Button>
                    <Button onClick={() => setIsEditing(false)}>取消</Button>
                    <Button 
                      type="primary" 
                      onClick={() => {
                        if (blogPost) {
                          const updatedPost = {
                            ...blogPost,
                            content: editContent,
                            updatedAt: new Date().toISOString()
                          };
                          setBlogPost(updatedPost);
                          setIsEditing(false);
                        }
                      }}
                    >
                      保存
                    </Button>
                  </Space>
                </div>
                
                {preview ? (
                  <div style={{ padding: '16px', border: '1px solid #f0f0f0', borderRadius: '6px', minHeight: '300px', backgroundColor: '#fff' }}>
                    <ReactMarkdown
                      rehypePlugins={[rehypeRaw, rehypeHighlight]}
                      remarkPlugins={[remarkGfm]}
                      children={editContent}
                      components={components}
                    />
                  </div>
                ) : (
                  <textarea
                    value={editContent}
                    onChange={(e) => setEditContent(e.target.value)}
                    style={{
                      width: '100%',
                      height: '500px',
                      padding: '16px',
                      border: '1px solid #d9d9d9',
                      borderRadius: '6px',
                      fontSize: '14px',
                      lineHeight: '1.5',
                      fontFamily: 'Monaco, Menlo, "Ubuntu Mono", monospace',
                      resize: 'vertical',
                      outline: 'none',
                      transition: 'border-color 0.3s'
                    }}
                    onFocus={(e) => e.target.style.borderColor = '#40a9ff'}
                    onBlur={(e) => e.target.style.borderColor = '#d9d9d9'}
                  />
                )}
              </div>
            </div>
          </div>
        ) : (
          <>
            <div className="blog-content-with-nav">
              <div className="markdown-content">
                <ReactMarkdown
                  rehypePlugins={[rehypeRaw, rehypeHighlight]}
                  remarkPlugins={[remarkGfm]}
                  children={blogPost.content}
                  components={components}
                />
              </div>
            
              {/* 右侧导航栏 */}
              {headings.length > 0 && (
                <div className="sidebar-nav">
                  <div className="nav-title">文章目录</div>
                  <div className="nav-items">
                    {headings.map(renderNavItem)}
                  </div>
                </div>
              )}
            </div>
            
            <Divider />
            
            <div className="blog-tags">
              {blogPost.tags.map((tag, index) => (
                <Tag key={index} color="purple">
                  {tag}
                </Tag>
              ))}
            </div>
            
            <div className="blog-actions" style={{ marginTop: '20px' }}>
              <Button type="link" icon={<Link to="/blog">返回博客列表</Link>} />
            </div>
          </>
        )}
      </div>
    );
  };

  // 渲染博客列表
  const renderBlogList = () => {
    if (loading) {
      return <div style={{ textAlign: 'center', padding: '40px' }}>加载中...</div>;
    }

    if (blogPosts.length === 0) {
      return (
        <div style={{ textAlign: 'center', padding: '40px' }}>
          <Empty description="暂无博客文章" />
        </div>
      );
    }

    return (
      <div className="blog-list">
        <List
          itemLayout="vertical"
          dataSource={blogPosts}
          renderItem={item => (
            <List.Item
              key={item.id}
              actions={[
                <TagOutlined key="tags" />,
                ...item.tags.map((tag, index) => (
                  <Tag key={index} color="blue" className="tag-item">
                    {tag}
                  </Tag>
                ))
              ]}
            >
              <List.Item.Meta
                title={<Title level={4}><Link to={`/blog/${item.id}`}>{item.title}</Link></Title>}
                description={
                  <div className="blog-meta">
                    <Text type="secondary" className="blog-meta-item">
                      <UserOutlined /> {item.author}
                    </Text>
                    <Text type="secondary" className="blog-meta-item">
                      <CalendarOutlined /> {formatDate(item.createdAt)}
                    </Text>
                    <Text type="secondary" className="blog-meta-item">
                      <Tag color="blue">{item.category}</Tag>
                    </Text>
                  </div>
                }
              />
              <Paragraph ellipsis={{ rows: 3 }} className="blog-excerpt">
                {item.excerpt}
              </Paragraph>
              <Button type="primary">
                <Link to={`/blog/${item.id}`}>阅读更多</Link>
              </Button>
            </List.Item>
          )}
        />
      </div>
    );
  };

  return (
    <div className="blog-page">
      <div className="container">
        {id ? renderBlogPostDetail() : renderBlogList()}
      </div>
    </div>
  );
};

export default BlogPage;